<?php
add_mini_help('minimal');
require 'DB/db_data_loader.php';
$hist_data = get_historical_quantities();

if (count(get_subdivisions_associative()) == 0 || count(get_is_associative()) == 0 || count($hist_data["DATE"]) == 0) {
    echo "Duomenų apie padalinius ir informacines sistemas nėra. Pirma importuokite juos.";
    unset($hist_data);
} else {
    unset($hist_data);
    function selectable_list_html($className, $data = Array()) {
        $content = '';
        foreach ($data as $code => $title) {
            $content .= '<div class="' . $className . '" onclick="selectElement(this, \'' . $code . '\')">' . $title . '</div>';
        }
        return $content;
    }

    MainDesign::leftSubmenuBeginning("Minimali apkrova");
    if (isset($_GET['minWorkloadFor']) && $_GET['minWorkloadFor'] != 'subdivision') {
        $class2 = ' class="current"';
        $class1 = '';
    } else {
        $class2 = '';
        $class1 = ' class="current"';
    }
    $sidebar_content .= '
<ul class="minWorkloadSidebar">
    <li id="goToSubdivision""><a' . $class1 . ' href="?tab=minimal&minWorkloadFor=subdivision">Padalinių</a></li>
    <li id="goToIS"><a' . $class2 . ' href="?tab=minimal&minWorkloadFor=is">Informacinių sistemų</a></li>
</ul>';
    MainDesign::leftSubmenuEnding();

    if (isset($_GET['minWorkloadFor']) && $_GET['minWorkloadFor'] == 'is') {
        $minimalWorkloadFor = 'is';
        $is = get_is_associative();
    } else {
        $minimalWorkloadFor = 'subdivisions';
        $subdivisions = get_subdivisions_associative();
    }
    ?>
    <script type="text/javascript" src="Plugins/jquery.ba-hashchange.min.js"></script>
    <script type="text/javascript">
        var minimalWorkloadFor = '<?php echo $minimalWorkloadFor; ?>';
        var selectedSubdivision = null;
        var selectedIS = null;
        var timePeriod = null;
        var gotResponse = false;
        
        var options = [{multiSelect: false}];
        var appColumns = [
            {id:"type", name:"Nr.", field:"type", width:40, cssClass:"spreadsheet-cell"},
            {id:"startDate", name:"Laikotarpio pradžia", field:"startDate", width:145, cssClass:"spreadsheet-cell"},
            {id:"endDate", name:"Laikotarpio pabaiga", field:"endDate", width:145, cssClass:"spreadsheet-cell"},
            {id:"amount", name:"Prognozuojamas sugaištas laikas (h)", field:"amount", width:225, cssClass:"spreadsheet-cell"}
        ];
        var appData;
        
        /**
         * Atžymi anksčiau pasirinktą padalinį, pažymi naują
         */
        function selectElement(el, code){
            previousSelection = document.getElementById('selectedElement');
            if(previousSelection != null) previousSelection.id = null;
            el.id = 'selectedElement';
            if(minimalWorkloadFor == 'subdivisions')
                selectedSubdivision = code;      
            else
                selectedIS = code;
        }
        function otherTimePeriodSelect() {
            jQuery('[name="otherTimePeriod"]').first().focus();
            timePeriod = jQuery('[name="otherTimePeriod"]').first().val();
        }
        function searchForPeriods(){
            if(minimalWorkloadFor == 'subdivision' && selectedSubdivision == null){
                alert("Nepasirinkote padalinio");
                return;
            }
            if(selectedSubdivision != null){
                selection = "&selectedSubdivision="+selectedSubdivision;
            }
            if(minimalWorkloadFor == 'is' && selectedIS == null){
                alert("Nepasirinkote informacinės sistemos");
                return;
            } 
            if(selectedIS != null){
                selection = "&selectedIS="+selectedIS;
            }
            if(timePeriod == null || timePeriod == ''){
                alert("Nepasirinkote/neįrašėte laikotarpio");
                return;
            }
            if(minimalWorkloadFor == 'subdivisions'){
                typeHash = 'subdivision='+selectedSubdivision;
                $('#minimalWorkflowTitle').html('Padalinio: "'+$('#selectedElement').html()+'" minimalios apkrovos periodai laikotarpiui:');
            }
            if(minimalWorkloadFor == 'is'){
                typeHash = 'informationSystem='+selectedIS;
                $('#minimalWorkflowTitle').html('"'+$('#selectedElement').html()+'" informacinės sitemos minimalios apkrovos periodai laikotarpiui:');
            }
            if(jQuery('[name="timePeriod"][value="other"]').first().attr('checked')){
                location.hash = typeHash+'&timeperiod=other|'+timePeriod;
                $('#minimalWorkflowTitle').html($('#minimalWorkflowTitle').html()+ ' '+timePeriod+' dienų');
            }
            else {
                location.hash = typeHash+'&timeperiod='+timePeriod;
                $('#minimalWorkflowTitle').html($('#minimalWorkflowTitle').html()+ ' '+$('input[name="timePeriod"]:checked').parent().text());
                                                                                       
            }
            jQuery('#minimalWorkFlowFilter').slideUp('fast', function(){
                jQuery('#changefilters').show();
                //if (!gotResponse) 
                //    jQuery('#minmalWorkflowContent').append('<div class="centeredMessage">Laukiame atsakymo iš serverio</div>');
            });
            
            gotResponse = false;
            $.ajax({
                type: "POST",
                url: "index.php",
                data: "real_action_script=Processing/MinimalWorkflow/MinimalWorkflow.php&ajax_request=true&timePeriod="+timePeriod+selection
            }).done(function( msg ) {
                gotResponse = true;
                eval(msg);
                jQuery('#minimalWorkflowTable').height(appData.length*25+35);
                appGrid = new Slick.Grid("#minimalWorkflowTable", appData, appColumns, options);
                appGrid.setSelectionModel(new Slick.CellSelectionModel(options)); 
                jQuery('#minmalWorkflowContent').show();
                i = 0;
                while(appData[i]['amount'] == appData[0]['amount']){
                    jQuery('.slick-row[row='+i+']').addClass('best');
                    i++;
                }
            });
        }
        function showFilter(){
            jQuery('#changefilters').hide();
            jQuery('#minimalWorkFlowFilter').slideDown('fast', null);
        }
        function changeRadioToOther() {
            jQuery('[name="timePeriod"][value="other"]').first().attr('checked', 'checked');
            timePeriod = jQuery('[name="otherTimePeriod"]').first().val();
        }
    </script>
    <button type="button" id="changefilters" onclick="showFilter()">Keisti paieškos parametrus</button>

    <div id="minimalWorkFlowFilter">
        Pasirinkite <?php echo ($minimalWorkloadFor == 'is') ? 'informacinę sistemą' : 'padalinį'; ?>:
        <div class="selectableElementList">
            <?php
            if ($minimalWorkloadFor == 'subdivisions')
                echo selectable_list_html('subdivision', $subdivisions);
            if ($minimalWorkloadFor == 'is')
                echo selectable_list_html('informationSystem', $is);
            ?>
        </div>
        <div class="selectableTimePeriod">
            Pasirinkite laikotarpį:<br />
            <?php if ($minimalWorkloadFor == 'subdivisions') : ?>
                <label><input type="radio" name="timePeriod" value="7" onchange="timePeriod=7" />Kvalifikacijos kėlimas (7 dienos)</label><br />
                <label><input type="radio" name="timePeriod" value="repair" onchange="timePeriod=-1"  />Patalpų remontas (du mėnesiai; žiemą - trys)</label><br />
                <?php
            endif;
            if ($minimalWorkloadFor == 'is') :
                ?>
                <label><input type="radio" name="timePeriod" value="3" onchange="timePeriod=3" />IS atnaujinimas (3 dienos)</label><br />
            <?php endif; ?>
            <label><input type="radio" name="timePeriod" value="other" onchange="otherTimePeriodSelect()" />Kita (įveskite)</label> 
            <input type="text" name="otherTimePeriod" class="decimal" onchange="timePeriod=this.value" onfocus="changeRadioToOther()" /> dienų<br />
        </div>
        <button type="button" onclick="searchForPeriods()">Ieškoti minimalios apkrovos periodų</button>
    </div>
    <div id="minmalWorkflowContent">
        <div id="minimalWorkflowTitle"></div>
        <div id="minimalWorkflowTable" style="width:560px;"></div>
        <div id="minimalWorkflowTableCaption">Žalsvai paryškintos eilutės su geriausiais variantais. Laikotarpio pradžia - įtraukiama; laikotarpio pabaiga - neįtraukiama</div>
    </div>


    <script type="text/javascript">
        $(window).hashchange( function(){
            var rawHashData = location.hash.substr(1, location.hash.length-1).split('&');
            for (i = 0; i < rawHashData.length; i++) {
                data = rawHashData[i].split('=');
                if(data[0] == 'subdivision'){
                    selectedSubdivision = data[1];
                    jQuery(".subdivision").each(function(index){
                        if(jQuery(this).attr("onclick").toString().indexOf(data[1].toUpperCase()+"'") != -1)
                            jQuery(this).attr("id", 'selectedElement');
                        return;
                    })
                }
                if(data[0] == 'informationSystem'){
                    selectedIS = data[1];
                    jQuery(".informationSystem").each(function(index){
                        if(jQuery(this).attr("onclick").toString().indexOf(data[1].toUpperCase()+"'") != -1)
                            jQuery(this).attr("id", 'selectedElement');
                        return;
                    })
                }
                if(data[0] == 'timeperiod'){
                    _timePeriod = data[1].split('|');
                    jQuery('[name="timePeriod"][value="'+_timePeriod[0]+'"]').first().attr('checked', 'checked');
                    jQuery('[name="otherTimePeriod"]').val(_timePeriod[1]);
                    if(_timePeriod[0] != 'other')
                        timePeriod = _timePeriod[0]
                    else timePeriod = _timePeriod[1]
                }
            }
            if((selectedSubdivision != null || selectedIS != null) && timePeriod != null && timePeriod != ''){
                searchForPeriods();
            }
        })
        
        $(window).hashchange();

        nmDecimal(".decimal");
    </script>

    <?
}